<?php

namespace Modules\Admin\Services;

use App\Exceptions\BusinessException;
use App\Helpers\CodeResponse;
use App\Services\BaseService;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Modules\Admin\Entities\Admin;
use Modules\Auth\Services\TokenService;
use Modules\Permission\Services\RoleService;

class AdminService extends BaseService
{
    public function Add(array $data): Admin
    {
        return DB::transaction(function () use ($data) {
            $data = collect($data);
            $data->offsetSet('password', Hash::make($data->get('password')));
            $admin = Admin::query()->create($data->toArray());
            return $admin;
        });
    }


    /**
     *
     * @param $username 登录账号
     * @param $password 登录密码
     *
     * @return bool
     * @author LL
     */
    public function AccountPasswordVerification($username, $password): bool
    {
        $admin = new Admin();
        $admin = $admin->findForPassport($username);
        if ($admin) {
            return Hash::check($password, $admin->password);
        }
        return false;
    }

    public function RefreshToken($refresh_token)
    {
        return TokenService::getInstance()->RefreshToken(
            $refresh_token,
            [
                'client_id' => config("admin.client_id"),
                'client_secret' => config("admin.client_secret"),
            ]
        );
    }

    /**
     * 重置密码
     *
     * @param        $user
     * @param string $password
     *
     * @return mixed
     * @author LL
     */
    public function ResetPassword($user, string $password)
    {
        $user->password = Hash::make($password);
        if (!$user->save()) {
            throw new BusinessException(CodeResponse::UPDATE_FAIL, '修改密码失败');
        }
        TokenService::getInstance()->tokenAllRevoked($user);
    }

    public function isTheUsernameAvailable(string $useranem, $excludeId = null)
    {
        if (Admin::where('username', $useranem)->where('id', '<>', $excludeId)->exists()) {
            throw new BusinessException(CodeResponse::REJECT_OPERATION, '用户名被占用');
        }
        return true;
    }

    public function Update(Admin $admin, array $data): Admin
    {
        $data = collect($data);
        if ($data->has('username')) {
            $this->isTheUsernameAvailable($data->get('username'), $admin->id);
        }

        if ($data->has('password')) {
            $data->offsetSet('password', Hash::make($data->get('password')));
        }

        $this->updateFail($admin->update($data->only(['username', 'name', 'super_admin', 'password', 'mobile', 'enable_status'])->toArray()));

        return $admin;
    }

    public function Destroy(Admin $admin)
    {
        $admin->delete();
    }
}
